﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
#pragma warning disable 0649
namespace PlutoStudio.Configuration
{
    [Export]
    public class Configuration<T> where T : class
    {
        [ImportMany(typeof(IConfigurationProvider), AllowRecomposition = true, RequiredCreationPolicy = CreationPolicy.NonShared)]
        private IEnumerable<Lazy<IConfigurationProvider, IConfigurationMeta>> providers;

        public T Value
        {
            get
            {
                return GetConfigurationInternal();
            }
        }

        private T GetConfigurationInternal()
        {
            var type = typeof(T);
            var provider = providers.Where(p => p.Metadata.Type.Equals(typeof(T))).OrderByDescending(p=>p.Metadata.Order);
            foreach (var item in provider)
            {
                var result= (item.Value as IConfigurationProvider<T>).GetConfig();
                if (result!=null)
                {
                    return result;
                }
            }
            return null;
        }

        public static T GetValue()
        {
            var container = MefContainer.Container;
            var config = container.GetExportedValue<Configuration<T>>();
            return config.GetConfigurationInternal();
        }

    }
}
